//
//  GQHFreightsController.m
//  Xanthium
//
//  Created by GuanQinghao on 07/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model
#import "GQHFreightModel.h"

#pragma mark Object

#pragma mark View
#import "GQHFreightsView.h"

#pragma mark Controller
#import "GQHFreightsController.h"

#import "GQHRoutesController.h"
#import "GQHFreightInfoController.h"
#import "GQHRegionController.h"
#import "GQHModelController.h"

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHFreightsController () <GQHFreightsViewDelegate> {
    
#pragma mark Data
    /// 找货请求参数
    __block NSMutableDictionary *freightParameters;
    /// 返回模型数组
    __block NSMutableArray<GQHFreightModel *> *freightModelArray;
    
    __block int _page;
#pragma mark View
    /// 自定义根视图
    GQHFreightsView *rootView;

}

@end


@implementation GQHFreightsController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHFreightsView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    freightParameters = [NSMutableDictionary dictionary];
    [freightParameters setObject:USER_GET_ID forKey:@"token"];
    [freightParameters setObject:ROWS forKey:@"rows"];
    [freightParameters setObject:@"01" forKey:@"releaseState"];
    
    rootView.qh_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [freightParameters setObject:@"" forKey:@"origin"];
        [freightParameters setObject:@"" forKey:@"destination"];
        [freightParameters setObject:@"" forKey:@"source"];
        [freightParameters setObject:@"" forKey:@"demandModels"];
        [freightParameters setObject:@"" forKey:@"keyWord"];
        rootView.textField.text = @"";
        
        [freightParameters setObject:[NSNumber numberWithInt:_page] forKey:@"page"];
        
        [self pullRefresh:freightParameters];
    }];
    
    [rootView.qh_tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_leftButton.hidden = YES;
    self.qh_titleLabel.text = @"找货";
    [self.qh_rightButton setTitle:@"路线" forState:UIControlStateNormal];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [rootView.qh_tableView.mj_header endRefreshing];
}

#pragma mark --Delegate

//搜索
- (void)searckKeyWords:(NSString *)keyWord
{
    [freightParameters setObject:keyWord forKey:@"keyWord"];
    [self fetchFreightsWithParameters:freightParameters];
}

/// 点击列表项
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    GQHFreightInfoController *freightInfoController = [[GQHFreightInfoController alloc] init];
    freightInfoController.qh_freightModel = freightModelArray[indexPath.row];
    freightInfoController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:freightInfoController animated:YES];
}

/// 点击选择起始地
- (void)qh_checkDeparture:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    GQHRegionController *regionController = [[GQHRegionController alloc] init];
    regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
    {
        DLog(@"%@--%@",regionID, regionName);
        
        if (regionID) {
            
//            [button setTitle:regionName forState:UIControlStateNormal];
            [freightParameters setObject:regionID forKey:@"origin"];
            [self fetchFreightsWithParameters:freightParameters];
        } else {
            
//            [button setTitle:@"起始地" forState:UIControlStateNormal];
            [freightParameters setObject:@"" forKey:@"origin"];
            [self fetchFreightsWithParameters:freightParameters];
        }
    };
    regionController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regionController animated:YES];
}

/// 点击选择目的地
- (void)qh_checkDestination:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    GQHRegionController *regionController = [[GQHRegionController alloc] init];
    regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
    {
        DLog(@"%@--%@",regionID, regionName);
        
        if (regionID) {
            
//            [button setTitle:regionName forState:UIControlStateNormal];
            [freightParameters setObject:regionID forKey:@"destination"];
            [self fetchFreightsWithParameters:freightParameters];
        } else {
            
//            [button setTitle:@"目的地" forState:UIControlStateNormal];
            [freightParameters setObject:@"" forKey:@"destination"];
            [self fetchFreightsWithParameters:freightParameters];
        }
    };
    regionController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regionController animated:YES];
}

/// 点击选择来源类型
- (void)qh_checkType:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"全部" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
//        [button setTitle:@"全部" forState:UIControlStateNormal];
        [freightParameters setObject:@"" forKey:@"source"];
        [self fetchFreightsWithParameters:freightParameters];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"我关注的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [button setTitle:@"我关注的" forState:UIControlStateNormal];
        [freightParameters setObject:@"我关注的" forKey:@"source"];
        [self fetchFreightsWithParameters:freightParameters];
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

/// 点击选择更多
- (void)qh_checkMore:(UIButton *)sender {
    
    __block UIButton *button = sender;
    
    /// 需求车型
    GQHModelController *modelController = [[GQHModelController alloc] init];
    modelController.qh_modelBlock = ^(NSString *modelID, NSString *modelName) {
        
        if (modelID) {
            
//            [button setTitle:modelName forState:UIControlStateNormal];
            [freightParameters setObject:modelID forKey:@"demandModels"];
            [self fetchFreightsWithParameters:freightParameters];
        } else {
            
//            [button setTitle:@"更多" forState:UIControlStateNormal];
            [freightParameters setObject:@"" forKey:@"demandModels"];
            [self fetchFreightsWithParameters:freightParameters];
        }
    };
    
    modelController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:modelController animated:YES];
}

/// 拨打电话
- (void)qh_dialMobile:(UIButton *)sender {
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        DLog(@"拨打电话");
        GQHFreightModel *freightModel = freightModelArray[sender.tag];
        if ([freightModel.qh_state isEqualToString:@"01"])
        {
            [self qh_dialWithMobile:freightModel.qh_posterMobile];
        }
    } unallowed:nil];
}

#pragma mark --TargetMethod
-(void)qh_clickedRightButton:(UIButton *)sender {
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        DLog(@"路线");
        
        GQHRoutesController *routesController = [[GQHRoutesController alloc] init];
        routesController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:routesController animated:YES];
    } unallowed:nil];
}

#pragma mark --PrivateMethod
- (void)fetchFreightsWithParameters:(NSMutableDictionary *)parameters {
    
    [self pullRefresh:freightParameters];
    
    
    rootView.qh_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        _page++;
        [parameters setObject:[NSNumber numberWithInt:_page] forKey:@"page"];
        
        [GQHFreightModel qh_fetchFreightsWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHFreightModel *> *freights) {
            
            if (status) {
                
                if (freights && freights.count > 0) {
                    
                    [freightModelArray addObjectsFromArray:freights];
                    rootView.qh_freightModelArray = freightModelArray;
                    [rootView.qh_tableView reloadData];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [rootView.qh_tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                
                [self showToastWithText:message];
                [rootView.qh_tableView.mj_footer endRefreshing];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_footer endRefreshing];
        }];
    }];
}

- (void)pullRefresh:(NSMutableDictionary *)parameters
{
    [GQHFreightModel qh_fetchFreightsWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHFreightModel *> *freights) {
        
        if (status) {
            
            freightModelArray = [NSMutableArray arrayWithArray:freights];
            rootView.qh_freightModelArray = freightModelArray;
            [rootView.qh_tableView reloadData];
            
        } else {
            
            [self showToastWithText:message];
        }
        
        [rootView.qh_tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
        
        [rootView.qh_tableView.mj_header endRefreshing];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
